package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.dubbo.api.db.QuestionApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.server.interceptors.UserHolder;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.RecommendUserQueryParam;
import com.tanhua.vo.RecommendUserVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;


@Service
public class RecommendService {

    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;


    public ResponseEntity queryTodayBest() {
//        调用mongo的服务 返回RecommendUser
        RecommendUser recommendUser = recommendUserApi.queryTodayBest(UserHolder.getUserId());
        if(recommendUser==null){ //新用户登录后 大数据还没有来得及推荐
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(88.0);
//            recommendUser.setUserId(RandomUtils.nextLong(1,99));
//            recommendUser.setScore(RandomUtils.nextDouble(80,95));
        }


//           根据返回RecommendUser的userId调用db的服务 返回UserInfo
        Long userId = recommendUser.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
//        RecommendUser+ UserInfo==>RecommendUserVO
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo,recommendUserVo);
//        少两个 tags  fateValue
//        String tags = userInfo.getTags();//"单身,本科,年龄相仿 "==>[单身,本科,年龄相仿]
        if(userInfo.getTags()!=null){
            recommendUserVo.setTags(userInfo.getTags().split(","));
        }
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        return ResponseEntity.ok(recommendUserVo);

    }

    public ResponseEntity queryRecommendation(RecommendUserQueryParam param) {
//        虽然说param中有7个参数，但是我们只用到了两个
//        param.getPage();param.getPagesize();
//        查询mongo，返回PageResult<RecommendUser>

       PageResult pageResult = recommendUserApi.queryRecommendation(UserHolder.getUserId(),param.getPage(),param.getPagesize());
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();
//        判断是否有推荐人  recommendUserList是否为空
        if(CollectionUtils.isEmpty(recommendUserList)){
            recommendUserList = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(RandomUtils.nextLong(1,99));
                recommendUser.setScore(RandomUtils.nextDouble(60,88));
                recommendUserList.add(recommendUser);
            }
        }

        /*recommendUserList.sort(new Comparator<RecommendUser>() {
            @Override
            public int compare(RecommendUser o1, RecommendUser o2) {
                return o2.getScore().intValue()-o1.getScore().intValue();
            }
        });*/
        recommendUserList.sort(((o1, o2) -> {
          return   o2.getScore().intValue()-o1.getScore().intValue();
        }));


        List<RecommendUserVo> list = new ArrayList<>();


//      根据RecommendUser中的userId查询UserInfo
        for (RecommendUser recommendUser : recommendUserList) {
            Long userId = recommendUser.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
//        RecommendUser+ UserInfo==>RecommendUserVO
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            BeanUtils.copyProperties(userInfo,recommendUserVo);
//        少两个 tags  fateValue
//        String tags = userInfo.getTags();//"单身,本科,年龄相仿 "==>[单身,本科,年龄相仿]
            if(userInfo.getTags()!=null){
                recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());

            list.add(recommendUserVo);
        }
        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);

    }

    public ResponseEntity queryPersonalInfo(Long userId) {
//        查询UserInfo
        UserInfo userInfo = userInfoApi.findById(userId);

        RecommendUserVo recommendUserVo = new RecommendUserVo();

        BeanUtils.copyProperties(userInfo,recommendUserVo);

        if(userInfo.getTags()!=null){
            recommendUserVo.setTags(userInfo.getTags().split(","));
        }

        Long score = recommendUserApi.queryScore(UserHolder.getUserId(),userId);

        recommendUserVo.setFateValue(score); //两个人（当前登录人和userId）的缘分值

        return ResponseEntity.ok(recommendUserVo);

    }

    @Reference
    private QuestionApi questionApi;

    public ResponseEntity queryStrangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return ResponseEntity.ok(question==null?"大海还是高山？": question.getTxt());
    }

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    public ResponseEntity replyStrangerQuestions(Integer userId, String reply) {

        Map<String, String> map = new HashMap<>();
        map.put("userId", UserHolder.getUserId().toString());  //发送方的id

        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

        map.put("nickname",userInfo.getNickname());
        Question question = questionApi.findByUserId(Long.parseLong(userId.toString()));

        map.put("strangerQuestion", question==null?"大海还是高山？": question.getTxt());
        map.put("reply", reply);
        String msg = JSON.toJSONString(map);
        huanXinTemplate.sendMsg(userId.toString(),msg);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity cards(int size) {
        PageResult pageResult = recommendUserApi.queryRecommendation(UserHolder.getUserId(), 1, size);
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();
        List<RecommendUserVo> list = new ArrayList<>();

//      根据RecommendUser中的userId查询UserInfo
        for (RecommendUser recommendUser : recommendUserList) {
            Long userId = recommendUser.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
//        RecommendUser+ UserInfo==>RecommendUserVO
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            BeanUtils.copyProperties(userInfo,recommendUserVo);
//        少两个 tags  fateValue
//        String tags = userInfo.getTags();//"单身,本科,年龄相仿 "==>[单身,本科,年龄相仿]
            if(userInfo.getTags()!=null){
                recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());

            list.add(recommendUserVo);
        }

        return ResponseEntity.ok(list);
    }

    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;


    public ResponseEntity love(Long likeUserId) {

//        当前用户是1号用户，右滑的是6号用户
//        1、记录到user_like表中
        userLikeApi.save(UserHolder.getUserId(),likeUserId);
//        userId    likeUserId
//          1           6

//         2、判断对方是否也喜欢当前登录人（怎么判断？？查询user_like）
//        如果6号喜欢过1号 在表中应该有这么一条数据
//        userId    likeUserId
//        6           1
        boolean exists = userLikeApi.exists(likeUserId,UserHolder.getUserId());

//        2.1 如果对方喜欢当前登录人
        if(exists){
//            想friend表中插入数据+ 两个人的好友关系注册到环信上
            friendApi.save(UserHolder.getUserId(),likeUserId);
//            userId   friendId
//              1        6
//              6        1
//            huanXinTemplate.contactUsers(UserHolder.getUserId(),likeUserId); //TODO 正式上线再放开

        }
//        2.2  如果对方不喜欢当前登录人
//         3、删除当前推荐的数据
        recommendUserApi.delete(UserHolder.getUserId(),likeUserId);

        return ResponseEntity.ok(null);


    }

    public ResponseEntity unlove(Long loveUserId) {
        recommendUserApi.delete(UserHolder.getUserId(),loveUserId);
        return ResponseEntity.ok(null);
    }
}
